<!DOCTYPE html>
<html lang="zh-cn">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    
    <title>CSS 变量教程 | liuz2&#39;s Blog</title>
    <meta name="viewport" content="width=device-width,minimum-scale=1">
    <meta name="generator" content="Hugo 0.63.1" />
    
    
      <META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">
    

    
    
      <link href="/dist/css/app.9576afd3b3c158d98f48ec5df01fec6a.css" rel="stylesheet">
    

    

    
      

    

    

    <meta property="og:title" content="CSS 变量教程" />
<meta property="og:description" content="CSS 变量是什么？有什么好处？和预处理器变量有什么不同？怎么用？" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://liuz2.gitee.io/posts/css-variable/" />
<meta property="article:published_time" content="2020-07-16T11:16:07+08:00" />
<meta property="article:modified_time" content="2020-07-16T11:16:07+08:00" />
<meta itemprop="name" content="CSS 变量教程">
<meta itemprop="description" content="CSS 变量是什么？有什么好处？和预处理器变量有什么不同？怎么用？">
<meta itemprop="datePublished" content="2020-07-16T11:16:07&#43;08:00" />
<meta itemprop="dateModified" content="2020-07-16T11:16:07&#43;08:00" />
<meta itemprop="wordCount" content="330">



<meta itemprop="keywords" content="css," /><meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="CSS 变量教程"/>
<meta name="twitter:description" content="CSS 变量是什么？有什么好处？和预处理器变量有什么不同？怎么用？"/>

	
  </head>

  <body class="ma0 avenir bg-white">

    
   
  

  <header>
    <div class="bg-black">
      <nav class="pv3 ph3 ph4-ns" role="navigation">
  <div class="flex-l justify-between items-center center">
    <a href="/" class="f3 fw2 hover-white no-underline white-90 dib">
      
        liuz2&#39;s Blog
      
    </a>
    <div class="flex-l items-center">
      

      
        <ul class="pl0 mr3">
          
          <li class="list f5 f4-ns fw4 dib pr3">
            <a class="hover-white no-underline white-90" href="/about/" title="About page">
              About
            </a>
          </li>
          
          <li class="list f5 f4-ns fw4 dib pr3">
            <a class="hover-white no-underline white-90" href="/links/" title="Links page">
              Links
            </a>
          </li>
          
          <li class="list f5 f4-ns fw4 dib pr3">
            <a class="hover-white no-underline white-90" href="/timeline/" title="Timeline page">
              Timeline
            </a>
          </li>
          
        </ul>
      
      















    </div>
  </div>
</nav>

    </div>
  </header>



    <main class="pb7" role="main">
      
  
  <article class="flex-l flex-wrap justify-between mw8 center ph3">
    <header class="mt4 w-100">
      <h1 class="f3 athelas mt3 mb1">CSS 变量教程</h1>
      
      
      <time class="f6 mv1 dib tracked" datetime="2020-07-16T11:16:07&#43;08:00">July 16, 2020</time>

      
      
    </header>
    <div class="nested-copy-line-height lh-copy sans-serif f5 nested-links nested-img mid-gray pr4-l w-two-thirds-l"><h2 id="css-变量是什么">CSS 变量是什么</h2>
<p><strong>CSS 变量</strong>（<em>CSS Variable</em>），更准确的名字是 <strong>CSS 自定义属性</strong>（<em>CSS custom properties</em>），是指以 <code>--</code> 开头的属性名称，比如 <code>--example-name</code>。其中的值可以通过 <code>var()</code> 在别处声明中引用。关于自定义变量的怪异命名方式，<em>Tab Atkins</em>（CSS 规范制订者之一）在<a href="https://www.xanthir.com/blog/b4KT0" title="Let's Talk about CSS Variables">一篇博文</a>中讲述了 CSS 变量背后的故事。</p>
<p>CSS 变量可以有效减少 CSS 的重复声明，而且也便于实现换肤等特效。Chrome 49 开始支持 CSS 变量。</p>
<p>自定义属性的值在它定义的元素上有效，并参与级联算法。</p>
<h2 id="和-css-预处理变量的不同">和 CSS 预处理变量的不同</h2>
<p>CSS 预处理器（比如 Less, SaSS）的变量和 CSS 变量有相似的地方，但是也有一些不同。</p>
<table>
<thead>
<tr>
<th>CSS 变量</th>
<th>CSS 预处理器变量</th>
</tr>
</thead>
<tbody>
<tr>
<td>动态</td>
<td>静态</td>
</tr>
<tr>
<td>可以级联</td>
<td>不可级联</td>
</tr>
<tr>
<td>可互操作</td>
<td>不可互操作</td>
</tr>
</tbody>
</table>
<h2 id="用法">用法</h2>
<p>语法如下：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-css" data-lang="css">:<span style="color:#a6e22e">root</span> {
    --somekeyword: <span style="color:#66d9ef">left</span>;
    --somecolor: <span style="color:#ae81ff">#0000ff</span>;
    --somecomplexvalue: <span style="color:#ae81ff">3</span><span style="color:#66d9ef">px</span> <span style="color:#ae81ff">6</span><span style="color:#66d9ef">px</span> rgb(<span style="color:#ae81ff">20</span>, <span style="color:#ae81ff">32</span>, <span style="color:#ae81ff">54</span>);
}
</code></pre></div><p>其中的 <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/:root" title=":root"><code>:root</code> 伪类</a>表示根元素，在 HTML 文档中指的就是 <code>html</code>。</p>
<p>注意，自定义属性是大小写敏感的。</p>
<p>使用样例：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-html" data-lang="html">&lt;<span style="color:#f92672">p</span> <span style="color:#a6e22e">id</span><span style="color:#f92672">=</span><span style="color:#e6db74">&#34;firstParagraph&#34;</span>&gt;
    This paragraph should have a blue background and yellow text.
&lt;/<span style="color:#f92672">p</span>&gt;
&lt;<span style="color:#f92672">p</span> <span style="color:#a6e22e">id</span><span style="color:#f92672">=</span><span style="color:#e6db74">&#34;secondParagraph&#34;</span>&gt;
    This paragraph should have a yellow background and blue text.
&lt;/<span style="color:#f92672">p</span>&gt;
&lt;<span style="color:#f92672">div</span> <span style="color:#a6e22e">id</span><span style="color:#f92672">=</span><span style="color:#e6db74">&#34;container&#34;</span>&gt;
    &lt;<span style="color:#f92672">p</span> <span style="color:#a6e22e">id</span><span style="color:#f92672">=</span><span style="color:#e6db74">&#34;thirdParagraph&#34;</span>&gt;
        This paragraph should have a green background and yellow text.
    &lt;/<span style="color:#f92672">p</span>&gt;
&lt;/<span style="color:#f92672">div</span>&gt;
</code></pre></div><div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-css" data-lang="css">:<span style="color:#a6e22e">root</span> {
    --first-color: <span style="color:#ae81ff">#488cff</span>;
    --second-color: <span style="color:#ae81ff">#ffff8c</span>;
}

#firstParagraph {
    <span style="color:#66d9ef">background-color</span>: <span style="color:#a6e22e">var</span>(<span style="color:#f92672">-</span><span style="color:#f92672">-</span><span style="color:#66d9ef">first</span><span style="color:#f92672">-</span><span style="color:#66d9ef">color</span>);
    <span style="color:#66d9ef">color</span>: <span style="color:#a6e22e">var</span>(<span style="color:#f92672">-</span><span style="color:#f92672">-</span>second<span style="color:#f92672">-</span><span style="color:#66d9ef">color</span>);
}

#secondParagraph {
    <span style="color:#66d9ef">background-color</span>: <span style="color:#a6e22e">var</span>(<span style="color:#f92672">-</span><span style="color:#f92672">-</span>second<span style="color:#f92672">-</span><span style="color:#66d9ef">color</span>);
    <span style="color:#66d9ef">color</span>: <span style="color:#a6e22e">var</span>(<span style="color:#f92672">-</span><span style="color:#f92672">-</span><span style="color:#66d9ef">first</span><span style="color:#f92672">-</span><span style="color:#66d9ef">color</span>);
}

#container {
    --first-color: <span style="color:#ae81ff">#48ff32</span>;
}

#thirdParagraph {
    <span style="color:#66d9ef">background-color</span>: <span style="color:#a6e22e">var</span>(<span style="color:#f92672">-</span><span style="color:#f92672">-</span><span style="color:#66d9ef">first</span><span style="color:#f92672">-</span><span style="color:#66d9ef">color</span>);
    <span style="color:#66d9ef">color</span>: <span style="color:#a6e22e">var</span>(<span style="color:#f92672">-</span><span style="color:#f92672">-</span>second<span style="color:#f92672">-</span><span style="color:#66d9ef">color</span>);
}
</code></pre></div><p><code>var()</code> CSS 函数支持默认值。即如果自定义属性不存在，则使用其余值当作默认值。</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-css" data-lang="css">.<span style="color:#a6e22e">component</span> .<span style="color:#a6e22e">header</span> {
    <span style="color:#75715e">/* 由于未设定 header-color，所以使用默认值 blue */</span>
    <span style="color:#66d9ef">color</span>: <span style="color:#a6e22e">var</span>(<span style="color:#f92672">-</span><span style="color:#f92672">-</span>header<span style="color:#f92672">-</span><span style="color:#66d9ef">color</span>, <span style="color:#66d9ef">blue</span>);
}
</code></pre></div><h2 id="响应式布局">响应式布局</h2>
<p>在响应式布局的 <code>media</code> 命令声明变量，可以实现不同屏幕的响应式变化：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-css" data-lang="css">:<span style="color:#a6e22e">root</span> {
    --font-size: <span style="color:#ae81ff">14</span><span style="color:#66d9ef">px</span>;
    --color: <span style="color:#ae81ff">#333</span>;
}

<span style="color:#f92672">p</span> {
    <span style="color:#66d9ef">font-size</span>: <span style="color:#a6e22e">var</span>(<span style="color:#f92672">-</span><span style="color:#f92672">-</span>font<span style="color:#f92672">-</span>size);
    <span style="color:#66d9ef">color</span>: <span style="color:#a6e22e">var</span>(<span style="color:#f92672">-</span><span style="color:#f92672">-</span><span style="color:#66d9ef">color</span>);
}

@<span style="color:#66d9ef">media</span> <span style="color:#f92672">screen</span> <span style="color:#f92672">and</span> <span style="color:#f92672">(</span><span style="color:#f92672">max-width</span><span style="color:#f92672">:</span> <span style="color:#f92672">320px</span><span style="color:#f92672">)</span> {
    :<span style="color:#a6e22e">root</span> {
        --font-size: <span style="color:#ae81ff">12</span><span style="color:#66d9ef">px</span>;
        --color: <span style="color:#66d9ef">red</span>;
    }
}
</code></pre></div><h2 id="兼容性处理">兼容性处理</h2>
<p>对于不支持 CSS 变量的浏览器，可以采用如下写法：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-css" data-lang="css"><span style="color:#f92672">a</span> {
    <span style="color:#66d9ef">color</span>: <span style="color:#ae81ff">#7f583f</span>;
    <span style="color:#66d9ef">color</span>: <span style="color:#a6e22e">var</span>(<span style="color:#f92672">-</span><span style="color:#f92672">-</span>primary);
}
</code></pre></div><p>也可以用 <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/@supports" title="@supports"><code>@supports</code> 命令</a>检测。</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-css" data-lang="css">@<span style="color:#66d9ef">supports</span> <span style="color:#f92672">(</span><span style="color:#f92672">--a</span><span style="color:#f92672">:</span> <span style="color:#f92672">0</span><span style="color:#f92672">)</span> {
    <span style="color:#75715e">/* supported */</span>
}

@<span style="color:#66d9ef">supports</span> <span style="color:#f92672">not</span> <span style="color:#f92672">(</span><span style="color:#f92672">--a</span><span style="color:#f92672">:</span> <span style="color:#f92672">0</span><span style="color:#f92672">)</span> {
    <span style="color:#75715e">/* not supported */</span>
}
</code></pre></div><p>目前 Chrome 49, Firefox 42, Safari 9.1 和 iOS Safari 9.3 均支持 CSS 变量。</p>
<h2 id="javascript-操作">JavaScript 操作</h2>
<p>JavaScript 也可以检测浏览器是否可以支持 CSS 变量：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-js" data-lang="js"><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">isSupported</span> <span style="color:#f92672">=</span>
    window.<span style="color:#a6e22e">CSS</span> <span style="color:#f92672">&amp;&amp;</span> window.<span style="color:#a6e22e">CSS</span>.<span style="color:#a6e22e">supports</span> <span style="color:#f92672">&amp;&amp;</span> window.<span style="color:#a6e22e">CSS</span>.<span style="color:#a6e22e">supports</span>(<span style="color:#e6db74">&#39;--a&#39;</span>, <span style="color:#ae81ff">0</span>);

<span style="color:#66d9ef">if</span> (<span style="color:#a6e22e">supported</span>) {
    <span style="color:#75715e">// supported
</span><span style="color:#75715e"></span>} <span style="color:#66d9ef">else</span> {
    <span style="color:#75715e">// not supported
</span><span style="color:#75715e"></span>}
</code></pre></div><p>JavaScript 操作 CSS 变量的写法如下：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-js" data-lang="js">document.<span style="color:#a6e22e">body</span>.<span style="color:#a6e22e">style</span>.<span style="color:#a6e22e">setProperty</span>(<span style="color:#e6db74">&#39;--primary&#39;</span>, <span style="color:#e6db74">&#39;#7F583F&#39;</span>);
document.<span style="color:#a6e22e">body</span>.<span style="color:#a6e22e">style</span>.<span style="color:#a6e22e">getPropertyValue</span>(<span style="color:#e6db74">&#39;--primary&#39;</span>).<span style="color:#a6e22e">trim</span>();
document.<span style="color:#a6e22e">body</span>.<span style="color:#a6e22e">style</span>.<span style="color:#a6e22e">removeProperty</span>(<span style="color:#e6db74">&#39;--primary&#39;</span>);
</code></pre></div><p>CSS 变量的高级用法，可以参考张鑫旭的<a href="https://www.zhangxinxu.com/wordpress/2020/07/css-var-improve-components/" title="CSS 变量对 JS 交互组件开发带来的提升与变革">这篇文章</a>。</p>
<h2 id="参考文档">参考文档</h2>
<ol>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties">Using CSS custom properties (variables)</a>, MDN</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/--*">Custom properties (&ndash;*): CSS Variables</a>, MDN</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/var">var()</a>, MDN</li>
<li><a href="https://www.ruanyifeng.com/blog/2017/05/css-variables.html">CSS 变量教程</a>，作者阮一峰，2017/05/09</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/@supports" title="@supports">@supports 命令</a>，MDN</li>
<li><a href="https://developers.google.cn/web/updates/2016/02/css-variables-why-should-you-care">CSS Variables: Why Should You Care? | Google Developers</a>, by <em>Rob Dodson</em>, 2019/01/14</li>
<li><a href="https://www.xanthir.com/blog/b4KT0" title="Let's Talk about CSS Variables">Let&rsquo;s Talk about CSS Variables</a>, by <em>Tab Atkins</em>, 2012/08/15</li>
<li><a href="https://philipwalton.com/articles/why-im-excited-about-native-css-variables/" title="Why I'm Excited About Native CSS Variables">Why I&rsquo;m Excited About Native CSS Variables</a>, by <em>Philip Walton</em>, 2015/12/06</li>
<li><a href="https://www.zhangxinxu.com/wordpress/2020/07/css-var-improve-components/" title="CSS 变量对 JS 交互组件开发带来的提升与变革">CSS 变量对 JS 交互组件开发带来的提升与变革</a>,作者张鑫旭，2020/07/01</li>
</ol>
<a href="https://gitee.com/liuz2/liuz2/blob/master/content/posts/css-variable.md#tree_comm_title" class="no-underline db b--black pa2 tc bg-black-90" style="color:#eee;">进入留言</a><ul class="pa0">
  
   <li class="list dib">
     <a href="/tags/css" class="link f5 grow no-underline br-pill ba ph3 pv2 mb2 dib black sans-serif">css</a>
   </li>
  
</ul>
<div class="mt6 instapaper_ignoref">
      
      
      </div>
    </div>

    <aside class="w-30-l mt6-l"><div class="bg-light-gray pa3 nested-list-reset nested-copy-line-height nested-links">
    <p class="f5 b mb3">目录</p>
      <nav id="TableOfContents">
  <ul>
    <li><a href="#css-变量是什么">CSS 变量是什么</a></li>
    <li><a href="#和-css-预处理变量的不同">和 CSS 预处理变量的不同</a></li>
    <li><a href="#用法">用法</a></li>
    <li><a href="#响应式布局">响应式布局</a></li>
    <li><a href="#兼容性处理">兼容性处理</a></li>
    <li><a href="#javascript-操作">JavaScript 操作</a></li>
    <li><a href="#参考文档">参考文档</a></li>
  </ul>
</nav>
  </div>




</aside>

  </article>

    </main>
    <footer class="bg-black bottom-0 w-100 pa3" role="contentinfo">
  <div class="flex justify-between">
  <a class="f4 fw4 hover-white no-underline white-70 dn dib-ns pv2 ph3" href="https://liuz2.gitee.io/" >
    &copy;  liuz2's Blog 2022 
  </a>
    <div>














</div>
  </div>
</footer>

    

  <script src="/dist/js/app.3fc0f988d21662902933.js"></script>


  </body>
</html>
